/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.controller.grant;

import com.google.common.base.Strings;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.result.BaseRespResult;
import com.je.core.entity.extjs.JSONTreeNode;
import com.je.rbac.annotation.ControllerAuditLog;
import com.je.rbac.cache.FuncPermissionCache;
import com.je.rbac.service.company.RbacDepartmentService;
import com.je.rbac.service.grant.RbacGrantFuncPermissionService;
import com.je.rbac.service.grant.RbacGrantMenuPermissionService;
import com.je.rbac.service.grant.department.RbacGrantDepartmentService;
import com.je.rbac.service.permission.GrantTypeEnum;
import com.je.rbac.service.permission.PermissionLoadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 部门授权
 */
@RestController
@RequestMapping(value = "/je/rbac/cloud/grant/department")
public class RbacGrantDepartmentController extends AbstractPlatformController {

    @Autowired
    private RbacGrantDepartmentService rbacGrantDepartmentService;
    @Autowired
    private RbacGrantMenuPermissionService rbacGrantMenuPermissionService;
    @Autowired
    private RbacGrantFuncPermissionService rbacGrantFuncPermissionService;
    @Autowired
    private RbacDepartmentService rbacDepartmentService;
    @Autowired
    private PermissionLoadService permissionLoadService;
    @Autowired
    private FuncPermissionCache funcPermissionCache;

    /**
     * 加载公司组织树
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"/loadDepartmentTree"}, method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "角色授权模块",operateTypeCode = "loadDepartmentTree",operateTypeName = "加载部门树",logTypeCode = "securityManage",logTypeName = "安全管理")
    public BaseRespResult loadDepartmentTree(HttpServletRequest request) {
        String companyIds = getStringParameter(request, "companyIds");
        String refresh = getStringParameter(request, "refresh");
        //清空缓存并重新加载
        if ("1".equals(refresh)) {
            funcPermissionCache.clear();
            permissionLoadService.reloadAllDepartmentPermCache();
        }

        JSONTreeNode rootNode;
        if (Strings.isNullOrEmpty(companyIds)) {
            rootNode = rbacDepartmentService.buildCompanyTreeData(false);
        } else {
            rootNode = rbacDepartmentService.buildCompanyTreeData(false, companyIds.split(","));
        }
        return BaseRespResult.successResult(rootNode);
    }

    /**
     * 加载公司部门人员树
     *
     * @param request
     * @return
     */
//    @AuthCheckPermission(value = {"pc-plugin-JE_CORE_RBAC-show"})
    @RequestMapping(value = {"/loadtDepartmentUserTree"}, method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public BaseRespResult loadtDepartmentUserTree(HttpServletRequest request) {
        String companyIds = getStringParameter(request, "companyIds");
        JSONTreeNode rootNode;
        if (Strings.isNullOrEmpty(companyIds)) {
            rootNode = rbacGrantDepartmentService.buildCompanyDepartmentUserOrgStrTree();
        } else {
            rootNode = rbacGrantDepartmentService.buildCompanyDepartmentUserOrgStrTree(companyIds.split(","));
        }
        return BaseRespResult.successResult(rootNode);
    }

    /**
     * 查询部门人员
     *
     * @param request
     * @return
     */
//    @AuthCheckPermission(value = {"pc-plugin-JE_CORE_RBAC-show"})
    @RequestMapping(value = {"/loadRoleUser"}, method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public BaseRespResult loadtUser(HttpServletRequest request) {
        String roleIds = getStringParameter(request, "roleIds");
        if (Strings.isNullOrEmpty(roleIds)) {
            return BaseRespResult.errorResult("请选择要查询的角色！");
        }
        List<Map<String, Object>> roleUsers = rbacGrantDepartmentService.findRoleUsers(roleIds);

        return BaseRespResult.successResult(roleUsers);
    }

    /**
     * 保存部门菜单授权
     *
     * @param request
     * @return
     */
//    @AuthCheckPermission(value = {"pc-plugin-JE_CORE_RBAC-show"})
    @RequestMapping(value = {"/saveDeptMenuPermission"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "角色授权模块",operateTypeCode = "saveDepartmentMenuPermission",operateTypeName = "更新部门菜单授权",logTypeCode = "securityManage",logTypeName = "安全管理")
    public BaseRespResult saveDeptMenuPermission(HttpServletRequest request) {
        String deptIds = getStringParameter(request, "deptIds");
        String addedStrData = getStringParameter(request, "addedStrData");
        String deletedStrData = getStringParameter(request, "deletedStrData");
        if (Strings.isNullOrEmpty(addedStrData) && Strings.isNullOrEmpty(deletedStrData)) {
            return BaseRespResult.errorResult("无数据操作！");
        }
        //更新权限
        rbacGrantMenuPermissionService.updateDeptMenuPermissions(GrantTypeEnum.MENU, deptIds, addedStrData, deletedStrData);
        return BaseRespResult.successResult("保存授权成功！");
    }

    /**
     * 保存功能授权
     *
     * @param request
     * @return
     */
//    @AuthCheckPermission(value = {"pc-plugin-JE_CORE_RBAC-show"})
    @RequestMapping(value = {"/saveDeptFuncPermission"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "角色授权模块",operateTypeCode = "saveDepartmentFuncPermission",operateTypeName = "更新部门功能授权",logTypeCode = "securityManage",logTypeName = "安全管理")
    public BaseRespResult saveDeptFuncPermission(HttpServletRequest request) {
        String deptIds = getStringParameter(request, "deptIds");
        String addedStrData = getStringParameter(request, "addedStrData");
        String deletedStrData = getStringParameter(request, "deletedStrData");
        if (Strings.isNullOrEmpty(addedStrData) && Strings.isNullOrEmpty(deletedStrData)) {
            return BaseRespResult.errorResult("无数据操作！");
        }
        rbacGrantFuncPermissionService.updateDepartmentFuncPermissions(GrantTypeEnum.FUNC, deptIds, addedStrData, deletedStrData);
        return BaseRespResult.successResult("保存授权成功！");
    }

    /**
     * 保存APP授权
     *
     * @param request
     * @return
     */
//    @AuthCheckPermission(value = {"pc-plugin-JE_CORE_RBAC-show"})
    @RequestMapping(value = {"/saveDeptAppPermission"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "角色授权模块",operateTypeCode = "saveDepartmentAppPermission",operateTypeName = "更新部门APP授权",logTypeCode = "securityManage",logTypeName = "安全管理")
    public BaseRespResult saveDeptAppPermission(HttpServletRequest request) {
        return BaseRespResult.errorResult("此版本不包括此功能！");
    }

}
